package com.lagou.edu.mvcframework;

import com.lagou.edu.annotion.*;
import com.lagou.edu.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class LgDispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<String>();

    private Map<String, Object> ioc = new HashMap<String, Object>();

//    private Map<String,Method> handlerMap = new HashMap<String,Method>();

    private List<Handler> handlerMap = new ArrayList<>();

    @Override
    public void init(ServletConfig config) {
        try {
            //1 加载配置文件 springmvc.properties
            String contextConfigLocation = config.getInitParameter("contextConfigLocation");
            doloadConfig(contextConfigLocation);
            //2 扫描相关的类，扫描注解
            doScan(properties.getProperty("scanPackage"));
            //3 初始化bean对象（实现ioc容器，基于注解形式）
            doInstance();
            //4 实现依赖注入
            doAutoWored();
            //5 构造一个HandlerMapping处理器映射器。将配置好的URL和Method建立映射关系
            initHandlerMapping();
            System.out.println("初始化完成");
            //6 等待请求进入，处理请求
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 构造一个HandlerMapping处理器映射器。将配置好的URL和Method建立映射关系
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取当前遍历当前对象的class
            Class<?> aClass = entry.getValue().getClass();
            if (!aClass.isAnnotationPresent(LgController.class)) {
                continue;
            }
            //定义类注解变量数组
            String[] classUserNames = null;
            if (aClass.isAnnotationPresent(Security.class)) {
                Security security = aClass.getAnnotation(Security.class);
                classUserNames = security.value();
            }

            String baseUrl = "";
            if (aClass.isAnnotationPresent(LgRequestMapping.class)) {
                //如果类上有LgRequestMapping注解并配置了value。则获取类上的URL
                LgRequestMapping annotation = aClass.getAnnotation(LgRequestMapping.class);
                baseUrl = annotation.value();
            }
            //获取该类的所有方法
            Method[] methods = aClass.getMethods();
            //遍历方法
            for (int i = 0; i < methods.length; i++) {

                Method method = methods[i];
                //判断方法上是否有注解LgRequestMapping
                if (method.isAnnotationPresent(LgRequestMapping.class)) {
                    String methodurl = "";
                    LgRequestMapping annotation = method.getAnnotation(LgRequestMapping.class);
                    methodurl = annotation.value();
                    String url = baseUrl + methodurl;
                    //建立url 和methodURL之间的关系
                    Handler handler = new Handler(entry.getValue(), method, Pattern.compile(url));
                    if (classUserNames != null) {
                        handler.setNeedSecurity(true);
                        handler.setUsers(classUserNames);
                    }

                    //处理security注解
                    if (method.isAnnotationPresent(Security.class)) {
                        Security methodAnnotation = method.getAnnotation(Security.class);
                        String[] value = methodAnnotation.value();
                        handler.setNeedSecurity(true);
                        handler.setUsers(value);
                    }
                    //获取所有类型的参数
                    Parameter[] parameters = method.getParameters();
                    for (int j = 0; j < parameters.length; j++) {
                        Parameter p = parameters[j];
                        if (p.getType() == HttpServletRequest.class || p.getType() == HttpServletResponse.class) {
                            handler.getParamIndexMapping().put(p.getType().getSimpleName(), j);
                        } else {
                            handler.getParamIndexMapping().put(p.getName(), j);
                        }
                    }
                    //处理参数以及参数位置
                    handlerMap.add(handler);

                }
            }
        }
    }

    /**
     * 实现依赖注入
     */
    private void doAutoWored() throws IllegalAccessException {
        //判断IOC是否为空
        if (ioc.isEmpty()) {
            return;
        } else {
            //遍历IOC中的所有对象，查看对象中的字段是否有@LgAutowried注解，如果有需要维护依赖注入关系
            for (Map.Entry<String, Object> entry : ioc.entrySet()) {
                // 获取bean中对象中的字段
                Field[] fields = entry.getValue().getClass().getDeclaredFields();
                //遍历判断处理
                for (int i = 0; i < fields.length; i++) {
                    Field field = fields[i];
                    //如果没有LgAutoeired注解
                    if (!field.isAnnotationPresent(LgAutowried.class)) {
                        continue;
                    } else {
                        //有@LgAutoeired注解
                        LgAutowried lgAutowried = field.getAnnotation(LgAutowried.class);
                        //获取注解的value值
                        String value = lgAutowried.value();
                        if ("".equals(value.trim())) {//没有配置bean的ID
                            value = field.getType().getName();
                        }
                        field.setAccessible(true);
                        field.set(entry.getValue(), ioc.get(value));
                    }
                }
            }
        }
    }

    /**
     * 初始化bean
     * 基于classNames缓存的权限定类型集合，以及反射技术完成对象的创建
     */
    private void doInstance() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        if (classNames.size() == 0) return;
        else {
            for (int i = 0; i < classNames.size(); i++) {
                String s = classNames.get(i);
                Class<?> aClass = Class.forName(s);
                //区分Controller和Service
                if (aClass.isAnnotationPresent(LgController.class)) {
                    //TODO controller的id此处不作特殊处理，不取value值。默认拿取类名的小写作为id保存到IOC容器中
                    String simpleName = aClass.getSimpleName();
                    String lowerCase = simpleName.toLowerCase();
                    Object o = aClass.newInstance();
                    ioc.put(lowerCase, o);
                } else if (aClass.isAnnotationPresent(LgService.class)) {
                    LgService annotation = aClass.getAnnotation(LgService.class);
                    String beanName = annotation.value();
                    //如果指定了value，则以value为IOC的key
                    if (!"".equals(beanName)) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        ioc.put(aClass.getSimpleName().toLowerCase(), aClass.getName());
                    }
                    // service层往往都是接口，面向接口开发。此时应该再以接口名为ID，放入一份对象IOC容器中。便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    if (interfaces.length > 0) {
                        for (int j = 0; j < interfaces.length; j++) {
                            Class<?> anInterface = interfaces[j];
                            //已接口的类型作为ID放入到IOC容器中
                            ioc.put(anInterface.getName(), aClass.newInstance());
                        }
                    }
                } else {
                    continue;
                }
            }
        }
    }

    /**
     * 扫描方法
     */
    private void doScan(String packageUrl) {
        //包所在的文件的绝对路径路径
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + packageUrl.replaceAll("\\.", "/");
        File file = new File(scanPackagePath);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {//判断子包是否是目录
                doScan(packageUrl + "." + file1.getName());
            } else if (file1.getName().endsWith(".class")) {
                String classPath = packageUrl + "." + file1.getName().replaceAll(".class", "");
                classNames.add(classPath);
            }
        }

    }

    /**
     * 加载配置文件
     *
     * @param contextConfigLocation
     */
    private void doloadConfig(String contextConfigLocation) {
        //将文件路径加载成流
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        System.out.println("resourceAsStream = " + resourceAsStream);
        //加载流到properties
        try {
            properties.load(resourceAsStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //根据URI获取到能够处理当前请求的handler
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }
        //参数绑定
        //获取所有参数类型数组，这个数组的长度就是我们最后要传入的args数组长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        //根据上述数组创建一个新的数组（参数数组，用于传入反射用）
        Object[] paravalues = new Object[parameterTypes.length];

        //一下就是为了向参数数组中塞值，而且还是保证参数顺序和方法形参顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();
        //定义变量userName传入的值
        String name="";
        //遍历请求参数
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            //name=?&name
            String value = StringUtils.join(param.getValue(), ",");
            //获取当前请求传递的username
            if("name".equals(param.getKey())){
                name = value;
            }
            //如果参数和方法中的参数匹配上了，填充数据
            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            } else {
                //确实有该参数，找到该参数顺序，
                Integer integer = handler.getParamIndexMapping().get(param.getKey());
                //把参数值填充到对应的位置中去
                paravalues[integer] = value;
            }
        }
        //判断是否需要鉴权
        if(handler.isNeedSecurity()==true){
            //判断当前路由访问用户是否满足白名单用户
            if(!Arrays.asList(  handler.getUsers()).contains(name)){
                resp.getWriter().write("No access !");
                return;
            }

        }

        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paravalues[requestIndex] = req;
        Integer responIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paravalues[responIndex] = resp;

        try {
            handler.getMethod().invoke(handler.getController(), paravalues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMap.isEmpty()) {
            return null;
        }
        String uri = req.getRequestURI();
        for (Handler handler : handlerMap) {
            Matcher matcher = handler.getPattern().matcher(uri);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }

}
